package com.fangsiqi.mashibing;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeCalculator {
	private LocalDateTime startTime;
	private LocalDateTime endTime;

	// 开始计时
	public void start() {
		this.startTime = LocalDateTime.now();
		System.out.println("开始时间: " + formatTime(startTime));
	}

	// 结束计时
	public void end() {
		this.endTime = LocalDateTime.now();
		System.out.println("结束时间: " + formatTime(endTime));
	}

	// 计算持续时间
	public Duration calculateDuration() {
		if (startTime == null || endTime == null) {
			throw new IllegalStateException("请先调用start()和end()方法");
		}
		return Duration.between(startTime, endTime);
	}

	// 获取格式化的持续时间
	public String getFormattedDuration() {
		Duration duration = calculateDuration();

		long hours = duration.toHours();
		long minutes = duration.toMinutesPart();
		long seconds = duration.toSecondsPart();
		long millis = duration.toMillisPart();

		return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis);
	}

	// 格式化时间
	private String formatTime(LocalDateTime time) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
		return time.format(formatter);
	}

	// 获取开始时间
	public LocalDateTime getStartTime() {
		return startTime;
	}

	// 获取结束时间
	public LocalDateTime getEndTime() {
		return endTime;
	}
}
